<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\common\model;

use app\admin\model\CarModel;
use app\admin\model\College;
use app\admin\model\Config;
use app\api\model\DouYinService;
use app\api\model\Token;
use app\common\model\AliPay;
use app\common\model\RebateLog;
use EasyWeChat\Factory;
use think\cache\driver\Redis;
use think\Exception;
use think\facade\Db;
use think\Model;
use util\Http;


class SourceModel extends Model
{
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;

    protected $table = 'yzn_source';

    public function cate()
    {
        return $this->belongsTo(CateModel::class, 'cid', 'id')->setEagerlyType(0);
    }


    public function getIndex($params = array())
    {
        $map = [];
        $map['yzn_source.status'] = 1;
        $map['yzn_source.is_lock'] = 0;
        if ($params['cid']) {
            $map['yzn_source.cid'] = $params['cid'];
        }
        $list = self::where($map)
            ->withJoin(['cate'])
            ->order("sort desc")
            ->paginate($params['limit'], false, ['page' => $params['page']]);
        foreach ($list as $row) {
            $row->getRelation('cate')->visible(['cate_name']);
            $row->visible(['id', 'title', 'annex', 'kind']);
        }
        //个人信息
        $user = (new StaffModel())->where(['id' => $params['uid']])->field('id,username,phone,avatar')->find();
        return ['code' => 200, 'msg' => '获取信息成功', 'data' => ['list' => $list, 'user' => $user]];
    }


    public function share($params = array())
    {
        try {
            $source = (new SourceModel())->where(['id' => $params['id']])->find();
            if (!$source) {
                throw new Exception('素材不存在，请刷新后重试');
            }
            if ($source['is_lock'] == 1) {
                throw new Exception('视频正在发布，请选择其他视频');
            }
            //锁住素材
            if (!(new SourceModel())->where(['id' => $params['id']])->update(['is_lock' => 1])) {
                throw new Exception('锁定失败，请重新尝试');
            }
            //查询今天已经发布了多少条
            $s = strtotime(date('Y-m-d') . '00:00:00');
            $l = strtotime(date('Y-m-d') . '23:59:59');
            $maps[] = ['status', '<>', 0];
            $maps[] = ['dy_id', '=', $params['dy_id']];
            $maps[] = ['create_time', '>', $s];
            $maps[] = ['create_time', '<', $l];
            $itemCount = (new ItemModel())->where($maps)->count();
            $limit = (new Config())->where(['name' => 'limit'])->value('value');
            if ($limit <= $itemCount) {
                throw new Exception('每日只能发布' . $limit . '条');
            }
            $douyin = (new DouYinService());
            $client_token = $douyin->getClientToken();
            $open_ticket = $douyin->getOpenTicket($client_token);
            $shareId = $douyin->getShareId($client_token);
            $signature = $this->createSdkSign($open_ticket);
            $pic = explode(',', $source['annex']);
            $path['url'] = $source['annex'];
            $path['kind'] = (int)$source['kind'];
            if (count($pic) > 1) {
                $path['url'] = json_encode($pic);
                $path['kind'] = 3;
            }
            $schemaPrams = [
                'share_type' => 'h5',
                'client_key' => config('config_douyin.dy_program.client_key'),
                'nonce_str' => $signature['nonce_str'],
                'timestamp' => (string)$signature['timestamp'],
                'signature' => $signature['sign'],
                'state' => $shareId,
                'path' => $path,
                'title' => $source['title'],
                'hashtag' => explode(',', $source['hashtag'])
            ];
            //保存记录
            $row = [
                'uid' => $params['uid'],
                'sid' => $params['id'],
                'source_id' => $shareId,
                'title' => $source['title'],
                'path' => $source['annex'],
                'kind' => $path['kind'],
                'create_time' => time(),
                'update_time' => time(),
                'hashtag' => $source['hashtag'],
                'cid' => $source['cid'],
            ];
            if (!(new ItemModel())->insert($row)) {
                throw new Exception('生成视频失败，请重新尝试');
            }
            return ['code' => 200, 'msg' => 'success', 'data' => $schemaPrams];


        } catch (Exception $e) {
            return ['code' => 201, 'msg' => $e->getMessage(), 'data' => $schemaPrams];
        }

    }


    public function createSdkSign($open_ticket)
    {
        $string = genRandomString(16);
        $time = time();
        $getSignParam = [
            'nonce_str' => $string,
            'ticket' => $open_ticket,
            'timestamp' => (string)$time,
        ];
        ksort($getSignParam);
        $queryStringParts = [];
        foreach ($getSignParam as $key => $value) {
            $queryStringParts[] = $key . "=" . $value;
        }
        $queryString = implode("&", $queryStringParts);
        return ['sign' => md5($queryString), 'timestamp' => $time, 'nonce_str' => $string];
    }


}
